package cn.tedu.boot07.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UploadController {
    @RequestMapping("/upload")
    public String upload(MultipartFile pic) throws IOException {
        System.out.println("pic = " + pic);
        //得到图片的原始文件名
        String fileName = pic.getOriginalFilename();
        System.out.println("原始文件名:"+fileName);
        //得到原始文件名的后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //得到唯一文件名UUID.randomUUID()获取唯一标识符
        fileName = UUID.randomUUID()+suffix;
        System.out.println("唯一文件名:"+fileName);
        //准备保存图片的路径
        String dirPath = "d:/files";
        File dirFile = new File(dirPath);
        //判断如果不存在,则创建文件夹
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        //得到文件的完整路径 d:/files/a.jpg
        String filePath = dirPath+"/"+fileName;
        //把图片保存到上面路径中 异常抛出
        pic.transferTo(new File(filePath));
        //把图片URL路径响应给客户端
        return "/"+fileName;
    }
    @RequestMapping("/remove")
    public void remove(String url) {
        new File("d:/files"+url).delete();
    }
}
